package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * MyBatis Plus 自动填充配置
 *
 * @author ruoyi
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            
            // 填充创建时间
            if (baseEntity.getCreateTime() == null) {
                this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
            }
            
            // 填充创建人
            if (baseEntity.getCreateBy() == null) {
                String username = SecurityUtils.getUsername();
                this.strictInsertFill(metaObject, "createBy", String.class, username);
            }
            
            // 填充更新时间
            if (baseEntity.getUpdateTime() == null) {
                this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
            }
            
            // 填充更新人
            if (baseEntity.getUpdateBy() == null) {
                String username = SecurityUtils.getUsername();
                this.strictInsertFill(metaObject, "updateBy", String.class, username);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            
            // 填充更新时间
            this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
            
            // 填充更新人
            if (baseEntity.getUpdateBy() == null) {
                String username = SecurityUtils.getUsername();
                this.strictUpdateFill(metaObject, "updateBy", String.class, username);
            }
        }
    }
}